package com.example.controller;

import com.example.dao.DepartmentDao;
import com.example.dao.EmployeeDao;
import com.example.pojo.Department;
import com.example.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    @RequestMapping("/emps")
    public String list(Model model){
        Collection<Employee>  employees = employeeDao.getAll();
        model.addAttribute("emps",employees);

        return "/emp/list";
    }

    @GetMapping("/emp")
    public String toAddPage(Model model){
        //查出所有部分的信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("Departments",departments);

        return "/emp/add";
    }

    @PostMapping("/emp")
    public String toAddEmp(Employee employee){
        //保存员工信息
        employeeDao.save(employee);
        //添加的操作 forward
        return "redirect:/emps";
    }

    @GetMapping("/emp/{id}")
    public String toUpdateEmp(@PathVariable("id") Integer id,Model model){
        //查出来原来得数据
        Employee employee = employeeDao.getEmployeeById(id);

        model.addAttribute("emp",employee);
        //查出所有部分的信息
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("Departments",departments);

        return "emp/update";
    }

    @PostMapping("/updateEmp")
    public String updateEmp(Employee employee){
        employeeDao.save(employee);

        return "redirect:/emps";
    }
    @GetMapping("/delemp/{id}")
    public String delEmp(@PathVariable("id") Integer id){
        employeeDao.deleteEmployeeById(id);
        return "redirect:/emps";
    }



}
